global root_dir = "`1'"

include "$root_dir/code/config/config.do"

cap noi log using ${log_dir}/patstat_2018b_tls231.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {

* This file makes the PRS_EPO_national_phase.csv
*originally an sql file, this imports tls 231 and reduces it to a more manegeable size


global patstat_in "${root_dir}/datasets/common_data/patstat_raw"
global patstat_tmp "${root_dir}/datasets/common_data/patstat_2018b/tmp"
global patstat_out "${root_dir}/datasets/common_data/patstat_2018b"


cap mkdir ${patstat_tmp}

forvalues xx = 1/34 {
    clear
    local part = cond(`xx' < 10, "0`xx'", "`xx'")
    insheet using ${patstat_in}/tls231_part`part'.txt, name
    
    keep if event_code == "PGFP"
    keep appln_id fee_country fee_payment_date fee_renewal_year
    rename fee_country country
    rename fee_payment_date payment_date
    rename fee_renewal_year renewal_year

    save ${patstat_tmp}/tls231_part`part'.dta, replace
}

use ${patstat_tmp}/tls231_part01.dta, clear
forvalues xx = 2/34 {
    local part = cond(`xx' < 10, "0`xx'", "`xx'")
    append using ${patstat_tmp}/tls231_part`part'.dta, force
}

sort appln_id

destring renewal_year, replace
replace renewal_year = 9999 if missing(renewal_year) | renewal_year == 0
format renewal_year %5.0f

destring payment_date, replace
replace payment_date = "9999-12-31" if missing(payment_date) | payment_date == ""

keep appln_id country
duplicates drop

save ${patstat_out}/PRS_EPO_national_phase.dta, replace

}

if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat